export default {
	namespaced: true,
	state: {

	},
	mutations: {

	},
	actions: {
		// 支付
		payAction(context, order) {
			return new Promise((resolve, reject) => {
				uni.$uv.http.post('/cadre/highSeasOrder/create', {
					"orderId": order.id, // 订单id
					"actualMoney": order.actualMoney,
					"openId": uni.getStorageSync('openId'), //"o3teo7TUE56DPl5hwQgm3kf7lB4I", // openId
					"description": "测试订单" // 订单名称
				}).then(res => {
					console.log('创建支付订单', res)
					if (res.code === 500) {
						uni.showToast({
							icon: 'error',
							title: res.msg
						});
					}
					wx.requestPayment({
						// "appid": "o3teo7Xv5JSlbXTloJodMobUUTOw", wx.getAccountInfoSync().miniProgram.appId,
						package: res.data.packageValue,
						nonceStr: res.data.nonceStr,
						timeStamp: res.data.timeStamp,
						paySign: res.data.paySign,
						signType: res.data.signType,
						success: function(pay) {
							var rawdata = JSON.parse(pay.rawdata);
							console.log("支付成功");
							resolve('支付成功')
						},
						fail: function(err) {
							console.log('支付失败:' + JSON.stringify(err));
							// that.cancelPayment(res.outTradeNo)
							console.log('res', res)
							context.dispatch('cancelPayment', res.data.outTradeNo)
							reject('支付失败')
						},
					});
				})
			})
		},
		cancelPayment(context, outTradeNo) {
			console.log('outTradeNo', outTradeNo)
			uni.$uv.http.get('/cadre/highSeasOrder/payStatus', {
				params: {
					outTradeNo
				}
			}).then(res => {
				console.log('取消支付', res)
			})
		},
		// 待收款列表
		fetchPendingTransfers() {
			uni.$uv.http.get('/cadre/highSeasOrder/transfer/pending').then(res => {
				if (res.code === 200 && Array.isArray(res.data)) {
					const pendingTransfers = res.data;
					if (res.data.length > 0) {
						const pendingPackageInfo = res.data[0].packageInfo;
						// 有待收款
						wx.requestMerchantTransfer({
							mchId: '1720508269',
							appId: wx.getAccountInfoSync().miniProgram.appId,
							package: pendingPackageInfo,
							success: (res) => {
								console.log('转账发起 success:', res);
								// 再调用后端接口查询状态
								const outBillNo = pendingTransfers[0].outBillNo;
								uni.$uv.http
									.get(`/cadre/highSeasOrder/transfer/status/${outBillNo}`)
									.then(statusRes => {
										if (statusRes.code === 200) {
											console.log('已确认收款', statusRes.data);
											// 刷新待收款列表
										}
									});
							},
							fail: (err) => {
								console.log('转账发起 fail:', err);
							},
						});
					} else {
						uni.$u.toast('暂无待确认收款');
					}
				}
			});
		},
	},
}